#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"

// using func_t = std::function<std::string(const std::string&)>;
typedef std::function<std::string(const std::string&)> func_t;


Log lg;

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR 
}; 

class UdpServer
{
    public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip):  sockfd_(0), port_(port), ip_(ip), isruning_(false)
    {

    }

    void Init()
    {
        //1创建udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal,"socket create errorr,sockfd:%d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socker creatr success,sockfd:%d", sockfd_);
        //2bind socket
        struct sockaddr_in local; //表示自己本地机器
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);//保证端口号是网络字节序列,htons作用是将主机序列转为网络序列(大端)
        //local.sin_addr.s_addr = inet_addr(ip_.c_str());//sin_addr.s_addr才是正真的类型(转到定义可查看),inet_addr是库里转类型函数 
        local.sin_addr.s_addr = INADDR_ANY;//绑定任意IP与 bing(ip=0) 的作用相同

        //上面完成了在用户区的变量定义,下面绑定到
        if(bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void Run(func_t func)
    {
        isruning_ = true;
        char inbuffer[size];


        while(isruning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
            //recvfrom是读取面向数据报的函数
            if(n < 0)
            {
                lg(Warning, "bind error, errno: %d, err string: %s", errno, strerror(errno));    
                continue;
            }
            inbuffer[n] = 0;

            std::string info = inbuffer;
            std::string echo_string = func(info);
            sendto(sockfd_, echo_string.c_str(), echo_string.size(), 0, (const sockaddr*)&client, len);
        }
    }

    ~UdpServer()
    {
        if (sockfd_ > 0) close(sockfd_);
    }

private:
    int sockfd_; //网络文件描述符
    std::string ip_;//任意地址绑定:bing(ip=0)
    uint16_t port_;//服务器端口号
    bool isruning_;
};

